<template>
	<view class="headBar">
		<u-search placeholder="请输入素材内容" v-model="keyword" @change="searchTextChange" @search="search"
			:showAction="false"></u-search>
		<u-button type="primary" :text="classActive===0?'选择分类':classList[classActive-1].name" shape="circle"
			customStyle="margin-left:14px;width:84px;height:32px;font-size:14px;" :color="primaryColor"
			@click="showClassPicker=true"></u-button>
	</view>
	<view v-if="swiperList.length > 0" class="swiper_c">
		<uni-swiper-dot :info="swiperList" :current="swiperCurrent" mode="round">
			<swiper class="swiper_box" @change="onSwiperChange" autoplay circular interval="3000">
				<swiper-item v-for="(item, index) in swiperList" :key="item.pic" @click="previewBanner(index)">
					<fr-image class="img" :src="imgHost + item.pic" lazy-load mode="aspectFill" radius="20rpx" />
				</swiper-item>
			</swiper>
		</uni-swiper-dot>
	</view>
	<view class="container">
		<u-scroll-list :indicatorActiveColor="primaryColor">
			<view v-for="(item, index) in classList" :key="item.cateId" class="nav" hover-class="hover"
				@click="onClassChange(index)">
				<u--image :src="imgHost+item.icon" width="56px" height="56px" :lazy-load="true"></u--image>
				<view class="title" :class="{active:classActive-1===index}">{{item.name}}</view>
			</view>
		</u-scroll-list>
	</view>
	<view class="page">
		<list reqUrl="/api/sucai/list" :reqData="reqData" :immediatecheck="false" ref="listInstance" formatData
			:handleFormat="handleFormat">
			<template v-slot="{ list }">
				<view class="list" v-for="item in list" :key="item.scId">
					<u-avatar :src="userInfo.head_img" size="50"></u-avatar>
					<view class="right">
						<view class="nick one-line">{{userInfo.nickname || '默认昵称'}}</view>
						<view class="content">
							<u-read-more showHeight="200rpx" toggle color="#62687f" fontSize="12px" textIndent="0">
								<view class="text">{{item.content}}</view>
							</u-read-more>
						</view>
						<view class="photos">
							<u-album :urls="item.imgList"></u-album>
						</view>
						<view class="actionBar">
							<view class="area">
								<view class="bar" :class="{show:item.showAction}">
									<view class="item" hover-class="hover" @click="operation(0,item)">
										<u-icon name="file-text" color="#fff" size="18px"></u-icon>
										<text>复制文案</text>
									</view>
									<view class="item" hover-class="hover" @click="operation(1,item)">
										<u-icon name="share" color="#fff" size="18px"></u-icon>
										<text>分享</text>
									</view>
									<view v-if="userInfo&&(userInfo.is_dis===1||userInfo.is_agent===1)" class="item"
										hover-class="hover" @click="operation(2,item)">
										<u-icon name="photo" color="#fff" size="18px"></u-icon>
										<text>海报</text>
									</view>
								</view>
							</view>
							<view class="action" hover-class="tapstate" @click.stop="item.showAction=!item.showAction">
								<u-icon name="more-dot-fill" color="#62687f" size="18px"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</template>
		</list>
	</view>
	<!--分类选择弹出层-->
	<u-picker :show="showClassPicker" :columns="[[{name:'全部'},...classList]]" keyName="name" title="请选择分类"
		:confirmColor="primaryColor" closeOnClickOverlay :defaultIndex="[classActive]" @close="showClassPicker=false"
		@cancel="showClassPicker=false" @confirm="onConfirmChooseClass"></u-picker>
	<!--海报图片选择弹出层-->
	<u-popup :show="showPosterImgPopup" @close="showPosterImgPopup=false" closeable>
		<view class="posterImgPopupWrap">
			<view class="title">点击图片，生成海报</view>
			<uni-swiper-dot :info="posterImgList" :current="posterImgCurrent" mode="round">
				<swiper class="swiper_box" @change="onPosterImgChange" autoplay circular interval="3000">
					<swiper-item v-for="item in posterImgList" :key="item" @click="toGeneratePoster(item)">
						<fr-image class="img" :src="item" lazy-load mode="heightFix" radius="10rpx" />
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</view>
	</u-popup>
	<!--海报预览弹出层-->
	<u-popup :show="showPosterPopup" @close="showPosterPopup=false" closeable mode="center">
		<view class="posterPopupWrap">
			<image :src="posterImg" class="posterImg" mode="heightFix" />
			<view class="tip">长按保存至手机</view>
		</view>
	</u-popup>
	<canvas :style="canvasStyle" class="poster_canvas" canvas-id="poster" id="poster" type="2d"></canvas>
	<!--设置分享内容成功后提示弹出层-->
	<!-- #ifdef H5 -->
	<u-overlay :show="showSetShareInfoOkPopup" @click="showSetShareInfoOkPopup = false" :opacity="0.7">
		<view class="showSetShareInfoOkPopup">
			<view class="guideLineWrap">
				<image src="/static/image/guide.png" class="guideLine" mode="widthFix" />
			</view>
			<view class="tip">
				<text>设置成功，点击右上方</text>
				<u-icon name="more-dot-fill" color="#fff" size="38rpx"></u-icon>
				<text>分享</text>
			</view>
			<view class="closeWrap">
				<u-icon name="close" color="#fff" size="38rpx"></u-icon>
			</view>
		</view>
	</u-overlay>
	<!-- #endif -->
	<!--完善信息弹出层-->
	<u-modal :show="showImproveInformationModal" title="提示" content='请先完善个人信息，即将前往完善信息，是否立即前往？'
		:confirmColor="primaryColor" showCancelButton cancelText="关闭" confirmText="前往"
		@cancel="showImproveInformationModal=false"
		@confirm="showImproveInformationModal=false;$u.route('/pages/improveInformation/improveInformation')"></u-modal>
</template>

<script setup>
	import { ref, computed, nextTick } from 'vue';
	import request from '@/utils/common/request/index';
	import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
	import { useUserStore } from '@/store/modules/useUserStore';
	import { copy } from '@/utils/common/index.js';
	import { getImageInfo, sleep } from '@/utils/common/index';
	import { drawRoundRect, dealWords } from '@/utils/common/canvas';
	// #ifdef MP-WEIXIN
	import { getCanvasCtx, base64ToBinary, getCanvasImageObj } from '@/utils/mp-weixin/canvas';
	// #endif
	// #ifdef H5
	import { loadImg, getCurrentRoute, setShareCard } from '@/utils/h5/index';
	import { getHost } from '@/utils/common/index'
	// #endif
	import { useGetThemColor } from '@/hooks/useGetThemColor';


	const { primaryColor } = useGetThemColor();
	const { imgHost } = getApp().globalData;
	const userInfo = computed(() => {
		return useUserStore().value;
	});


	const classList = ref([]);
	const classActive = ref(0);
	const showClassPicker = ref(false);
	const getClassList = (isReqList = true) => {
		return request({
			url: '/api/sucai/cate',
			loadingTip: '加载中'
		}).then(data => {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 0
			});
			classList.value = data;
			isReqList && listInstance.value.resetRequest();
		});
	}
	getClassList();

	const onConfirmChooseClass = (e) => {
		const index = e.indexs[0];
		if (index === 0) {
			reqData.cateId = '';
			classActive.value = 0;
		} else {
			if (index === classActive.value) return;
			classActive.value = index;
			reqData.cateId = classList.value[index - 1].cateId;
		}

		showClassPicker.value = false;
		listInstance.value.resetRequest();

	}
	const onClassChange = (index) => {
		if (index + 1 === classActive.value) return;
		classActive.value = index + 1;
		reqData.cateId = classList.value[index].cateId;
		listInstance.value.resetRequest();
	}


	const keyword = ref('');
	const searchTextChange = (value) => {
		reqData.keywords = value;
		if (value === '') {
			listInstance.value.resetRequest();
		}
	};
	const search = () => {
		listInstance.value.resetRequest();
	};


	/**轮播图 */
	const swiperCurrent = ref(0);
	let swiperList = ref([]);
	const getBanner = () => {
		return request({
			url: '/api/bblist',
		}).then((res) => {
			swiperList.value = res;
		});
	};
	getBanner();
	const onSwiperChange = (e) => {
		swiperCurrent.value = e.detail.current;
	};
	const previewBanner = (index) => {
		if (swiperList.value.length === 0) return;
		const urls = swiperList.value.map((item) => {
			return imgHost + item.pic;
		});
		uni.previewImage({
			current: index,
			urls,
			loop: true,
			indicator: 'default',
		});
	};


	/**列表 */
	const listInstance = ref();
	let reqData = {
		cateId: '',
		keywords: ''
	};
	const handleFormat = (res) => {
		let data = res.data;
		data.forEach((item) => {
			item.showAction = false;
			item.imgList = item.imgList.map(item => imgHost + item);
		});
		return data;
	};

	const showImproveInformationModal = ref(false);
	const operation = (type, item) => {
		if (type === 0) {
			copy(item.content, false);
			uni.showToast({
				title: "文案复制成功，点击图片长按图片可将图片保存至手机相册",
				icon: "none",
				duration: 3000
			});
		} else if (type === 1) {
			if (userInfo.value && userInfo.value.is_perfect_info === 2) {
				return showImproveInformationModal.value = true;
			}
			// #ifdef H5
			setShareInfoInit(item);
			// #endif
		} else if (type === 2) {
			if (userInfo.value && userInfo.value.is_perfect_info === 2) {
				return showImproveInformationModal.value = true;
			}
			if (item.imgList.length === 0) return uni.showToast({
				title: '无图片素材，请复制文案！',
				icon: 'none'
			});
			posterImgList.value = item.imgList;
			posterImgCurrent.value = 0;
			showPosterImgPopup.value = true;
		}
		item.showAction = false;
	}


	// #ifdef H5
	const showSetShareInfoOkPopup = ref(false);
	const setShareInfoInit = (info) => {
		const { host } = getHost();
		const shareLink = host + '/terminal/#/pages/home/home';

		setShareCard(
			info.cateName,
			info.content,
			shareLink,
			info.imgList[0]
		).then(() => {
			setShareDataSuccess(); // 设置成功
		}).catch(() => {
			uni.showToast({
				title: '设置失败',
				icon: 'error'
			})
		})
	}

	function setShareDataSuccess() {
		if (!showSetShareInfoOkPopup.value) showSetShareInfoOkPopup.value = true;
	}
	// #endif


	/**下拉刷新事件 */
	onPullDownRefresh(() => {
		reqData.cateId = '';
		classActive.value = 0;
		Promise.all([getClassList(false), getBanner(), listInstance.value.resetRequest()]).finally(() => {
			uni.stopPullDownRefresh();
		});
	});
	// * 页面触底事件，不能删除，否则不能触发list组件触底事件
	onReachBottom(() => {});

	//海报相关
	let qrCodeImg = ref('');
	request({
		url: '/api/appbindp',
		method: 'POST',
		data: {
			redirect_path: ``
		}
	}).then(res => {
		qrCodeImg.value = res;
	})
	const showPosterImgPopup = ref(false);
	const posterImgList = ref([]);
	const posterImgCurrent = ref(0);
	const onPosterImgChange = (e) => {
		posterImgCurrent.value = e.detail.current;
	};

	let posterImg = ref('');
	const posterWidth = 375;
	let postHeight = ref(0);
	const canvasStyle = computed(() => {
		return `width:${posterWidth}px;height:${postHeight.value}px;`;
	})
	const toGeneratePoster = async imgUrl => {
		showPosterImgPopup.value = false;
		uni.showLoading({
			title: '处理中',
			mask: true
		});

		let bgImg = '';
		let currentY = 0;

		//海报图
		try {
			const imgInfo = await loadImg(imgUrl);
			bgImg = imgInfo.src;
			const bgImgHeight = posterWidth * imgInfo.height / imgInfo.width;
			currentY = bgImgHeight;
			postHeight.value = bgImgHeight + 100 * posterWidth / 375; //加上用户信息的位置高度
		} catch (e) {
			uni.hideLoading();
			return uni.showToast({
				title: '海报图片加载失败，请稍后再试！',
				icon: 'error'
			});
		}

		//头像
		let faceImg = '';
		try {
			const faceImgInfo = await loadImg(userInfo.value.head_img);
			faceImg = faceImgInfo.src;
		} catch (e) {
			uni.hideLoading();
			return uni.showToast({
				title: '用户头像加载失败，请稍后再试！',
				icon: 'error'
			});
		}

		//二维码 qrCodeImg
		let qrCodeImagePath = '';
		try {
			const qrCodeImgInfo = await loadImg(qrCodeImg.value);
			qrCodeImagePath = qrCodeImgInfo.src;
		} catch (e) {
			uni.hideLoading();
			return uni.showToast({
				title: '链接二维码加载失败，请稍后再试！',
				icon: 'error'
			});
		}

		await nextTick();
		await sleep(300);

		let that = this;
		// * 开始绘制整张海报背景
		// #ifdef H5
		let ctx = uni.createCanvasContext('poster', this);
		// #endif

		// #ifdef MP-WEIXIN
		let { ctx, canvas } = await getCanvasCtx('poster');
		// #endif

		// * 绘制整个面板
		ctx.clearRect(0, 0, posterWidth, postHeight.value);
		ctx.fillStyle = "#fff";
		ctx.fillRect(0, 0, posterWidth, postHeight.value);

		// * 绘制面板圆角
		// drawRoundRect(ctx, 0, 0, posterWidth, postHeight.value, 10);
		// * 绘制背景图片
		ctx.drawImage(bgImg, 0, 0, posterWidth, currentY);

		//预设宽度
		const facePosterWidth = 56 * posterWidth / 375;
		const qrCodePosterWidth = 70 * posterWidth / 375;

		//绘制头像
		currentY += 20 * posterWidth / 375;
		ctx.save();
		drawRoundRect(ctx, 10 * posterWidth / 375, currentY, facePosterWidth, facePosterWidth, facePosterWidth /
			2);
		ctx.drawImage(faceImg, 10 * posterWidth / 375, currentY, facePosterWidth, facePosterWidth);
		ctx.restore(); //跳出clip

		//绘制昵称
		ctx.fillStyle = '#333';
		currentY += 3 * posterWidth / 375;

		dealWords({
			ctx: ctx, //画布上下文
			fontSize: 16, //字体大小
			word: userInfo.value.nickname, //需要处理的文字
			maxWidth: posterWidth - qrCodePosterWidth - facePosterWidth - 10 * posterWidth /
				375, //一行文字最大宽度
			x: facePosterWidth + 23 * posterWidth / 375, //文字在x轴要显示的位置
			y: currentY, //文字在y轴要显示的位置
			maxLine: 1, //文字最多显示的行数
		});

		//绘制邀请文案
		ctx.fillStyle = '#666';
		currentY += 23 * posterWidth / 375;

		dealWords({
			ctx: ctx, //画布上下文
			fontSize: 12, //字体大小
			word: '邀请您来享受品牌会员权益', //需要处理的文字
			maxWidth: posterWidth - qrCodePosterWidth - facePosterWidth - 10 * posterWidth /
				375, //一行文字最大宽度
			x: facePosterWidth + 23 * posterWidth / 375, //文字在x轴要显示的位置
			y: currentY, //文字在y轴要显示的位置
			maxLine: 2, //文字最多显示的行数
		});

		//绘制二维码
		currentY = postHeight.value - qrCodePosterWidth - 15 * posterWidth / 375;
		// faceImg
		// qrCodeImagePath
		ctx.drawImage(qrCodeImagePath, posterWidth - qrCodePosterWidth - 10 * posterWidth /
			375, currentY, qrCodePosterWidth,
			qrCodePosterWidth);


		// #ifdef H5
		// * 绘制完毕
		ctx.draw(false, () => {
			uni.canvasToTempFilePath({
				destWidth: posterWidth,
				destHeight: postHeight.value,
				height: postHeight.value,
				canvasId: 'poster',
				success: res => {
					posterImg.value = res.tempFilePath;
					showPosterPopup.value = true;
				},
				fail: err => {
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					});
				},
				complete() {
					uni.hideLoading();
				}
			});
		});
		// #endif
	}

	const showPosterPopup = ref(false);
</script>

<style lang="scss" scoped>
	.headBar {
		position: sticky;
		top: 0;
		display: flex;
		align-items: center;
		padding: 10px 14px;
		z-index: 9;
		background-color: #fff;
	}

	.swiper_c {
		margin: 0 0 14px;

		.swiper_box {
			height: 320rpx;

			swiper-item {
				box-sizing: border-box;
				padding: 0 28rpx;
			}

			.img {
				width: 694rpx;
				height: 100%;
			}
		}

		::v-deep .uni-swiper__dots-item {
			height: 4px !important;
			width: 4px !important;
		}

		::v-deep .uni-swiper__dots-long {
			width: 15px !important;
		}

	}

	.nav {
		width: 56px;

		&+.nav {
			margin-left: 14px;
		}

		.title {
			margin-top: 4px;
			display: flex;
			justify-content: center;
			font-size: 12px;

			&.active {
				color: v-bind(primaryColor);
			}
		}
	}

	.list {
		margin-bottom: 20px;
		display: flex;
		border-bottom: 1px solid #f5f5f5;

		.right {
			flex: 1;
			padding-left: 14px;
			padding-bottom: 10px;

			.nick {
				padding-top: 2px;
				font-size: 16px;
				font-weight: 500;
				color: #62687f;
			}

			.content {
				padding: 10px 0;

				::v-deep .u-read-more__toggle {
					justify-content: flex-start !important;
				}

				.text {
					white-space: pre-line;
					line-height: 24px;
				}
			}

			.photos {
				padding-bottom: 14px;
			}

			.actionBar {
				display: flex;
				justify-content: flex-end;
				overflow: hidden;

				.area {
					overflow: hidden;
					padding-left: 10px;
				}

				.bar {
					transition: transform 300ms;
					will-change: transform;
					transform: translateX(101%);
					display: flex;
					align-items: center;
					padding: 4px 10px;
					background-color: #4F5054;
					border-radius: 5px;
					color: #fff;

					&.show {
						transform: translateX(-10px);
					}

					.item {
						display: flex;
						align-items: center;

						&+.item {
							margin-left: 10px;
						}
					}
				}

				.action {
					position: relative;
					z-index: 1;
					padding: 4px 10px;
					background-color: #f5f5f5;
					border-radius: 5px;
				}
			}
		}
	}

	.posterImgPopupWrap {
		.title {
			padding: 16px 0;
			text-align: center;
			color: #999;
		}

		.swiper_box {
			height: 50vh;

			.img {
				height: 90%;
			}

			::v-deep .fr_img {
				display: flex;
				justify-content: center;
			}
		}
	}

	.posterPopupWrap {
		padding: 4px 4px 10px;
		background-color: #fff;


		.posterImg {
			height: 88vh;
		}

		.tip {
			text-align: center;
			font-size: 12px;
			color: #999;
		}
	}

	.poster_canvas {
		position: fixed;
		top: 9999px;
	}

	.showSetShareInfoOkPopup {

		.guideLineWrap {
			display: flex;
			justify-content: flex-end;

			.guideLine {
				width: 70%;
				transform: translateX(100rpx);
			}
		}

		.tip {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 40rpx 0;
			font-size: 32rpx;
			color: #fff;
		}

		.closeWrap {
			display: flex;
			justify-content: center;
		}
	}
</style>